package cn.yuanqiao.web.controller.archive.supervision;

import java.io.*;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.common.core.context.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import cn.yuanqiao.archive.supervision.domain.SupervisionFile;
import cn.yuanqiao.archive.supervision.service.ISupervisionFileService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 督察指导附件Controller
 *
 * @author xy
 * @date 2023-08-01
 */
@RestController
@RequestMapping("/archive/supervisionFile")
public class SupervisionFileController extends BaseController
{
    @Autowired
    private ISupervisionFileService supervisionFileService;

    /**
     * 查询督察指导附件列表
     */
/*
    @PreAuthorize("@ss.hasPermi('archive:supervisionFile:list')")
*/
    @GetMapping("/list")
    public TableDataInfo list(SupervisionFile supervisionFile)
    {
/*
        startPage();
*/
        List<SupervisionFile> list = supervisionFileService.selectSupervisionFileList(supervisionFile);
        return getDataTable(list);
    }

    /**
     * 导出督察指导附件列表
     */
    @PreAuthorize("@ss.hasPermi('archive:supervisionFile:export')")
    @Log(title = "督察指导附件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SupervisionFile supervisionFile)
    {
        List<SupervisionFile> list = supervisionFileService.selectSupervisionFileList(supervisionFile);
        ExcelUtil<SupervisionFile> util = new ExcelUtil<SupervisionFile>(SupervisionFile.class);
        util.exportExcel(response, list, "督察指导附件数据");
    }

    /**
     * 获取督察指导附件详细信息
     */
    @PreAuthorize("@ss.hasPermi('archive:supervisionFile:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(supervisionFileService.selectSupervisionFileById(id));
    }

    /**
     * 新增督察指导附件
     */
    @PreAuthorize("@ss.hasPermi('archive:supervisionFile:add')")
    @Log(title = "督察指导附件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SupervisionFile supervisionFile)
    {
        return toAjax(supervisionFileService.insertSupervisionFile(supervisionFile));
    }

    /**
     * 修改督察指导附件
     */
    @PreAuthorize("@ss.hasPermi('archive:supervisionFile:edit')")
    @Log(title = "督察指导附件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SupervisionFile supervisionFile)
    {
        return toAjax(supervisionFileService.updateSupervisionFile(supervisionFile));
    }

    /**
     * 删除督察指导附件
     */
/*
    @PreAuthorize("@ss.hasPermi('archive:supervisionFile:remove')")
*/
    @Log(title = "督察指导附件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(supervisionFileService.deleteSupervisionFileByIds(ids));
    }

    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("id")Long id, MultipartFile file)
    {
        try {
            SupervisionFile supervisionFile = supervisionFileService.uploadFile(id,file);
            return AjaxResult.success(supervisionFile);
        }catch (Exception e){
            logger.error("上传文件失败", e);
            return AjaxResult.error("上传失败！"+e.getMessage());
        }
    }

    @PostMapping("/view")
    public void view(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long id=Long.parseLong(request.getParameter("id"));

        SupervisionFile supervisionFile=supervisionFileService.selectSupervisionFileById(id);
        String url=supervisionFile.getDocMnt()+supervisionFile.getPath();
        if (url.equals("null")){
            response.sendError(404, "File not found!");
            return;
        }
        response.reset(); // 非常重要
        // 设置 CORS 响应头
        ResponseUtils.defaultResponse(response);
        //在线预览，浏览器支持的文件类型都能打开
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "inline; filename=" + supervisionFile.getDocName());
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(url)));
        byte[] buf = new byte[1024];
        int len = 0;
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        System.gc();
        br.close();
        out.close();
    }

    @PostMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response)throws Exception{
        Long id=Long.parseLong(request.getParameter("id"));

        SupervisionFile supervisionFile=supervisionFileService.selectSupervisionFileById(id);
        String filePath=supervisionFile.getDocMnt()+supervisionFile.getPath();
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            //return ResponseData.error("File not found!");
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        // 设置 CORS 响应头
        ResponseUtils.defaultResponse(response);
        String  fileName= supervisionFile.getDocName();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        br.close();
        out.close();
    }
}
